package com.woniu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.domain.*;
import com.woniu.dto.Result;
import com.woniu.dto.StatusCode;
import com.woniu.service.*;
import com.woniu.utils.JwtUtils;
import com.woniu.vo.ConditionVo;
import com.woniu.vo.PositionAndCompany;
import com.woniu.vo.UserAndToken;
import com.woniu.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.domain.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.domain.Resume;
import com.woniu.domain.User;
import com.woniu.dto.Result;
import com.woniu.dto.StatusCode;
import com.woniu.service.UserService;
import com.woniu.utils.SendCodeUtil;
import com.woniu.vo.UserAndRole;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.woniu.service.UserService;
import com.woniu.service.impl.UserServiceImpl;
import com.woniu.vo.UserAllInterviewsVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.woniu.service.UserService;
import com.woniu.utils.Mysalt;
import com.woniu.vo.PasswordVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;

import java.util.List;
import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zyy
 * @since 2021-03-05
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户服务接口信息")//用于描述接口类的相关信息，作用于类上
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserVoService userVoService;

    @Resource
    private ResumeService resumeService;

    @Resource
    private CompanyService companyService;

    @Resource
    private FeedbackService feedbackService;

    @Resource
    private PositionService positionService;

    /**
     * @Author Lints
     * @Date 2021/3/6/006 10:49
     * @Description 检测数据库中是否有此名字，有则可以登录，无则考虑前去注册
     * @Param [username]
     * @Return com.woniu.dto.Result
     * @Since version-1.0
     */
    @GetMapping("checkName/{username}")
    public Result register(@PathVariable String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username).or().eq("tel",username);
        User userDB = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(userDB)){
            return new Result(false, StatusCode.MUCHNAME,"用户名不存在，可去注册");
        }
        return new Result(true, StatusCode.OK,"用户名合法");
    }


    /**
     * @Author Lints
     * @Date 2021/3/6/006 11:21
     * @Description 用户登录
     * @Param [userVo]
     * @Return com.woniu.dto.Result
     * @Since version-1.0
     */
    @PostMapping("login")
    public Result login(@RequestBody UserVo userVo){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userVo.getUsername()).or().eq("tel",userVo.getUsername());
        User userDB = userService.getOne(queryWrapper);
        Md5Hash md5Hash = new Md5Hash(userVo.getPassword(), userDB.getSalt(), 1024);
        String md5Password = md5Hash.toHex();
        if(userDB.getPassword().equals(md5Password)){
            //登陆成功
            HashMap<String, String> map = new HashMap<>();
            map.put("username",userVo.getUsername());
            String jwtToken = JwtUtils.getCodeToken(map);
            UserAndToken  userAndToken=new UserAndToken();
            userAndToken.setJwtToken(jwtToken);
            userAndToken.setUser(userDB);
            return new Result(true, StatusCode.OK,"登陆成功",userAndToken);
        }
        return new Result(false, StatusCode.IncorrectCredentials,"凭证错误");
    }

    /**
     * @Author Lints
     * @Date 2021/3/6/006 15:28
     * @Description 根据用户id查找其一二级用户菜单
     * @Param [uid]
     * @Return com.woniu.dto.Result
     * @Since version-1.0
     */
    @GetMapping("getMenus/{uid}")
    public Result getMenus(@PathVariable Integer uid){
        Set<Permission> permissions=userService.getOneTwoMenus(uid);
        return new Result(true, StatusCode.OK,"获取全部菜单成功",permissions);
    }


    /**
     * @Author Lints
     * @Date 2021/3/8/008 13:27
     * @Description 用来做用户管理的求职者
     * @Param [conditionVo]
     * @Return com.woniu.dto.Result
     * @Since version-1.0
     */
    @GetMapping("getUserVo")
    public Result getUser(ConditionVo conditionVo){
        IPage<UserVo> jobUser = userVoService.getUser(conditionVo);
        return new Result(true, StatusCode.OK,"查询单个用户信息",jobUser);
    }

    /**
     * @Author Lints
     * @Date 2021/3/10/010 9:48
     * @Description 查询单个用户简历信息
     * @Param [uid]
     * @Return com.woniu.dto.Result
     * @Since version-1.0
     */


    @GetMapping("getResume/{uid}")
    public Result getResume(@PathVariable Integer uid){
        System.out.println("查询简历-------------------------------");
        QueryWrapper<Resume> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        return new Result(true, StatusCode.OK,"查询单个用户简历信息成功",resumeService.getOne(queryWrapper));
    }

    @DeleteMapping("deleteUserById/{uid}")
    public Result deleteUserById(@PathVariable Integer uid){
         userService.deleteUserById(uid);
        return new Result(true, StatusCode.OK,"删除单个用户成功！！！");
    }

    @GetMapping("getCompany/{uid}")
    public Result getCompany(@PathVariable Integer uid){

        return new Result(true, StatusCode.OK,"查询单个用户公司信息成功",companyService.getCompanyInfo(uid));
    }


    @DeleteMapping("deleteCompanyUserById/{uid}")
    public Result deleteCompanyUserById(@PathVariable Integer uid){
        System.out.println("删除单个用户------");
        Company companyInfo = companyService.getCompanyInfo(uid);
        if(!ObjectUtils.isEmpty(companyInfo)){
            if(companyInfo.getUserCount()==1){
                companyService.removeById(companyInfo.getCompanyId());
                //删除该公司下面的所有职位
                List<Position> positions = positionService.deletePositinByCompanyId(companyInfo.getCompanyId());
                positions.forEach(position -> {
                    positionService.removeById(position);
                });
            }else if(companyInfo.getUserCount()>1){
                companyInfo.setUserCount(companyInfo.getUserCount()-1);
                companyService.updateById(companyInfo);
            }
        }
        userService.deleteCompanyUserById(uid);
        return new Result(true, StatusCode.OK,"删除单个用户成功！！！");
    }

    @PutMapping("updateUserById")
    public Result updateUserById(@RequestBody User user){
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), user.getSalt(), 1024);
        String md5Password = md5Hash.toHex();
        user.setPassword(md5Password);
        QueryWrapper<User> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("id",user.getId());
        boolean update = userService.update(user, updateWrapper);
        if (update){
            return new Result(true, StatusCode.OK,"修改管理员信息成功！！！");
        }
        return new Result(false, StatusCode.ERROR,"修改管理员信息失败！！！");
    }


    //注册时发送短信验证码
    @GetMapping("sendCode/{tel}")
    public Result sendCode(@PathVariable String tel){
        System.out.println(tel);
        String mobileCode = SendCodeUtil.sendCode(tel);

        return new Result(true,StatusCode.OK,"发送验证码成功",mobileCode);
    }

    //注册时验证用户名是否重复
    @GetMapping("registerName/{username}")
    public Result registerName(@PathVariable String username){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User userDB = userService.getOne(wrapper);
        if (ObjectUtils.isEmpty(userDB)) {
            return new Result(true,StatusCode.OK,"用户名尚未注册");
        }else{
            return new Result(false,StatusCode.MUCHNAME,"用户名已被注册");
        }

    }
    //注册时验证手机号是否重复
    @GetMapping("registerTel/{tel}")
    public Result registerTel(@PathVariable String tel) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("tel", tel);
        User userDB = userService.getOne(wrapper);
        if (ObjectUtils.isEmpty(userDB)) {
            return new Result(true, StatusCode.OK, "手机号尚未注册");
        } else {
            return new Result(false, StatusCode.MUCHNAME, "手机号已被注册");
        }
    }
    //用户注册
    @PostMapping("userRegister")
    public Result userRegister(@RequestBody UserAndRole userAndRole){
        System.out.println(userAndRole);
        Integer userId = userService.userRegister(userAndRole);
        return new Result(true,StatusCode.OK,"注册成功",userId);
    }
    //    求职者面试情况
//    1.1全部面试

    @ApiOperation(value = "求职者面试情况",notes = "<span style='color:red;'>用户全部面试</span>")
    @ApiImplicitParams({
            //dataType:参数类型
            //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
            @ApiImplicitParam(name = "positionId",value = "职位id",dataType = "Integer",paramType = "path",example = "java各工程师"),

    })
    @GetMapping("allInterviews")
    public Result allInterviews(Integer  uid){
//        Integer userId =3;
        List<UserAllInterviewsVo> strings = userService.interviewManagementData(uid);

        if (ObjectUtils.isEmpty(strings)) {
            return  new Result(false,StatusCode.OK,"失败");
        }
        return  new Result(true,StatusCode.OK,"成功",strings);
    }

    //    1.2 已接受面试
    @ApiOperation(value = "求职者面试情况已接受面试",notes = "<span style='color:red;'>用户已接受面试</span>")
    @ApiImplicitParams({
            //dataType:参数类型
            //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
            @ApiImplicitParam(name = "uid",value = "用户id",dataType = "Integer",paramType = "path",example = "java各工程师"),

    })
    @GetMapping("getAccepted")
    public Result Accepted(Integer  uid){
//        Integer userId =3;
        List<UserAllInterviewsVo> accepted = userService.accepted(uid);
        if (ObjectUtils.isEmpty(accepted)) {
            return  new Result(false,StatusCode.OK,"失败");
        }

        return  new Result(true,StatusCode.OK,"成功",accepted);
    }

//    1.3 待处理
@ApiOperation(value = "求职者面试情况待处理面试",notes = "<span style='color:red;'>用户待处理面试</span>")
@ApiImplicitParams({
        //dataType:参数类型
        //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
        @ApiImplicitParam(name = "uid",value = "用户id",dataType = "Integer",paramType = "path",example = "java各工程师"),

})
@GetMapping("getPendingProcessing")
public Result pendingProcessing(Integer  uid){
//    Integer userId =3;
    List<UserAllInterviewsVo> accepted = userService.pendingProcessing(uid);
    if (ObjectUtils.isEmpty(accepted)) {
        return  new Result(false,StatusCode.OK,"失败");
    }

    return  new Result(true,StatusCode.OK,"成功",accepted);
}


//    1.4已拒绝
@ApiOperation(value = "求职者面试情况已拒绝面试",notes = "<span style='color:red;'>用户已拒绝面试</span>")
@ApiImplicitParams({
        //dataType:参数类型
        //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
        @ApiImplicitParam(name = "uid",value = "用户id",dataType = "Integer",paramType = "path",example = "java各工程师"),

})
@GetMapping("getHasBeenRejected")
public Result HasBeenRejected(Integer  uid){
//    Integer userId =3;
    List<UserAllInterviewsVo> hasBeenRejected = userService.hasBeenRejected(uid);
    if (ObjectUtils.isEmpty(hasBeenRejected)) {
        return  new Result(false,StatusCode.OK,"失败");
    }

    return  new Result(true,StatusCode.OK,"成功",hasBeenRejected);
}



    //    我的申请
//    2.1 已申请


    @GetMapping("getHasApplied")
    @ApiOperation(value = "求职者我的申请已申请面试",notes = "<span style='color:red;'>用户已申请面试</span>")
    @ApiImplicitParams({
            //dataType:参数类型
            //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
            @ApiImplicitParam(name = "uid",value = "用户id",dataType = "Integer",paramType = "path",example = "java各工程师"),

    })
    public Result HasApplied(Integer  userId){
//        Integer userId =3;
        List<UserAllInterviewsVo> hasApplied = userService.hasApplied(userId);
        if (ObjectUtils.isEmpty(hasApplied)) {
            return  new Result(false,StatusCode.OK,"失败");
        }

        return  new Result(true,StatusCode.OK,"成功",hasApplied);
    }


    //2.我的申请
//    2.2 我的收藏
    @GetMapping("getMyCollection")
    @ApiOperation(value = "求职者我的申请我的收藏面试",notes = "<span style='color:red;'>用户我的收藏面试</span>")
    @ApiImplicitParams({
            //dataType:参数类型
            //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
            @ApiImplicitParam(name = "uid",value = "用户id",dataType = "Integer",paramType = "path",example = "java各工程师"),

    })
    public Result myCollection(Integer  userId){
//        Integer userId =3;
        List<UserAllInterviewsVo> myCollection = userService.myCollection(userId);
        if (ObjectUtils.isEmpty(myCollection)) {
            return  new Result(false,StatusCode.OK,"失败");
        }

        return  new Result(true,StatusCode.OK,"成功",myCollection);
    }


    //    我的收藏新增功能
    @GetMapping("insertCollection")
    @ApiOperation(value = "求职者我的申请我的收藏新增功能",notes = "<span style='color:red;'>用户我的收藏新增功能</span>")
    @ApiImplicitParams({
            //dataType:参数类型
            //paramType:参数由哪里获取     path->从路径中获取，query->?传参，body->ajax请求
            @ApiImplicitParam(name = "uid",value = "用户id",dataType = "Integer",paramType = "path",example = "java各工程师"),
            @ApiImplicitParam(name = "companyId",value = "公司id",dataType = "Integer",paramType = "path",example = "java各工程师"),
            @ApiImplicitParam(name = "positionId",value = "职位id",dataType = "Integer",paramType = "path",example = "java各工程师"),
    })
    public Result insertCollection(Integer companyId, Integer positionId, Integer userId){
        userId=3;
        int i = userService.insertCollection(companyId, positionId, userId);
        if(i<0){
            return  new Result(false,StatusCode.ERROR,"false");
        }
        return  new Result(true,StatusCode.ERROR,"true");
    }







    //查找用户的资料
    @GetMapping("findusername/{uid}")
    public Result<User>  findusername(@PathVariable Integer uid){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", uid);
        User user = userService.getOne(wrapper);
        return  new Result<>(true, StatusCode.OK, "查询成功",user);
    }

    //修改密码
    @PostMapping("updatapassword")
    public Result<User> updatapassword(@RequestBody PasswordVo passwordVo){

        String salt= Mysalt.getSalt(5);
        Md5Hash md5Hash = new Md5Hash(passwordVo.getPass(),salt,1024);
        User user = new User();
        user.setPassword(md5Hash.toHex());
        user.setSalt(salt);
        System.out.println(user);
        UpdateWrapper<User> wrapper = new UpdateWrapper();
        wrapper.eq("id", passwordVo.getUid());

        userService.update(user, wrapper);
        return new Result<>(true,StatusCode.OK,"修改成功");
    }
}

